package com.mingmen.supplier.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.lzy.imagepicker.ImagePicker;
import com.mingmen.supplier.R;
import com.mingmen.supplier.adapter.CommodityAdapter;
import com.mingmen.supplier.adapter.CommodityLabelAdapter;
import com.mingmen.supplier.adapter.NoticeListAdapter;
import com.mingmen.supplier.adapter.SearchAdapter;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.definerecycleview.SwipeRecyclerView;
import com.mingmen.supplier.defineview.ClearEditText;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.label.bean.LabelTestBean;
import com.mingmen.supplier.label.recycler.OnItemClickListener;
import com.mingmen.supplier.model.NoticeModel;
import com.mingmen.supplier.model.SearchModel;
import com.mingmen.supplier.popwindow.PopupWindowCompat;
import com.mingmen.supplier.refresh.ClassicsFooter;
import com.mingmen.supplier.refresh.ClassicsHeader;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class GongNoticeListActivity extends AppCompatActivity implements NoticeListAdapter.OnItemClickListener {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;

    private ImagePicker imagePicker;

    @BindView(R.id.btn_login)
    Button btn_login;

    private int resurtResurant = 100;
    @BindView(R.id.recycle_shopo)
    RecyclerView mRecyclerView;

    NoticeListAdapter commodityAdapter;

    List<NoticeModel.DataBean> dataList = new ArrayList<>();

    LinearLayoutManager linearLayoutManager;


    @BindView(R.id.view_dishline)
    View view_dishline;

    /*
        @BindView(R.id.btn_auditlist)
        Button btn_auditlist;*/
    String token;

    List<String> noticeIds = new ArrayList<>();
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    String keyword;
    TimePickerView pvTime;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;
    String startTime;
    String endTime;
    @BindView(R.id.layout_search)
    LinearLayout layout_search;
    @BindView(R.id.layout_second)
    LinearLayout layout_second;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.main_search)
    ClearEditText main_search;
    @BindView(R.id.layout_edit_search)
    LinearLayout layout_edit_search;
    @BindView(R.id.img_jingying)
    ImageView img_jingying;
    @BindView(R.id.img_shangjia)
    ImageView img_shangjia;
    //默认筛选当天数据
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gongnoticelist);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        token = (String) SharePreferenceUtil.get(this, "token", "");
        linearLayoutManager = new LinearLayoutManager(this);

//        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        getCaneda();

        commodityAdapter = new NoticeListAdapter(this, dataList);
        commodityAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(commodityAdapter);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());

        textview_calendafirst.setText(data);
        textview_calendasecond.setText(data);
        startTime = data;
        endTime = data;
        commodityAdapter.setOnItemClickListener(this);
//        getData(token, "", startTime, endTime, pageNumber);
        getData(token, "", "", "", pageNumber);
        refreshLayout.setRefreshHeader(new ClassicsHeader(GongNoticeListActivity.this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(GongNoticeListActivity.this));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (dataList.size() > 0) {
                    dataList.clear();
                }
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getData(token, "", "", "", pageNumber);
                refreshlayout.finishRefresh(200);//传入false表示刷新失败
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(GongNoticeListActivity.this, "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;

//                    getData(token, "", startTime, endTime, pageNumber);
                    HttpResponse.listAnnouncement(token, keyword, startTime, endTime, pageNumber, new StringCallback(GongNoticeListActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);

                            if (baseBean.getCode() == 0) {

                                NoticeModel noticeModel = new NoticeModel();
                                noticeModel = GsonUtil.GsonToBean(s, NoticeModel.class);
                                dataList.addAll(noticeModel.getData());
                                if (dataList.size() == 0) {
                                    mRecyclerView.setVisibility(View.GONE);
                                    layout_nodata.setVisibility(View.VISIBLE);
                                } else {
                                    mRecyclerView.setVisibility(View.VISIBLE);
                                    layout_nodata.setVisibility(View.GONE);
                                }
                                if (noticeIds.size() > 0) {
                                    noticeIds.clear();
                                }
                                for (int i = 0; i < dataList.size(); i++) {
                                    noticeIds.add(dataList.get(i).getId());
                                }
                                totalPage = noticeModel.getTotalPage();
                                commodityAdapter.setDataList(dataList);

                            } else if (baseBean.getCode() == 401) {
                                startActivity(new Intent(GongNoticeListActivity.this, LoginActivity.class));
                                finish();
                            } else {
                                Toast.makeText(GongNoticeListActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                            }


                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }
            }
        });
        main_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    getData(token, "", "", "", 1);
                } else {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getData(token, main_search.getText().toString(), "", "", 1);

                        }
                    }, 800);
                }


//                startActivityForResult(intent, resurtResurant);
            }
        });
        main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                getData(token, main_search.getText().toString(), "", "", 1);

                return false;
            }
        });


    }

    public void getData(String token, String keyword, String startTime, String endTime, int pageNumber) {
        HttpResponse.listAnnouncement(token, keyword, startTime, endTime, pageNumber, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (dataList.size() > 0) {
                    dataList.clear();
                }
                if (baseBean.getCode() == 0) {

                    NoticeModel noticeModel = new NoticeModel();
                    noticeModel = GsonUtil.GsonToBean(s, NoticeModel.class);
                    dataList.addAll(noticeModel.getData());
                    if (dataList.size() == 0) {
                        mRecyclerView.setVisibility(View.GONE);
                        layout_nodata.setVisibility(View.VISIBLE);
                    } else {
                        mRecyclerView.setVisibility(View.VISIBLE);
                        layout_nodata.setVisibility(View.GONE);
                    }
                    if (noticeIds.size() > 0) {
                        noticeIds.clear();
                    }
                    for (int i = 0; i < dataList.size(); i++) {
                        noticeIds.add(dataList.get(i).getId());
                    }
                    totalPage = noticeModel.getTotalPage();
                    commodityAdapter.setDataList(dataList);

                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(GongNoticeListActivity.this, LoginActivity.class));
                    finish();
                } else {
                    Toast.makeText(GongNoticeListActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }


            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }


    @OnClick({R.id.text_return, R.id.btn_login, R.id.linear_return, R.id.textview_calendafirst, R.id.layout_search, R.id.layout_second, R.id.btn_search, R.id.textview_calendasecond})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_return:
            case R.id.linear_return:
                finish();
                break;
            case R.id.btn_login:
                startActivity(new Intent(GongNoticeListActivity.this, NoticeSendActivity.class));

                break;

           /* case R.id.btn_auditlist:
                startActivity(new Intent(GongNoticeListActivity.this, AuditListActivity.class));
                break;*/
            case R.id.layout_search:
            case R.id.textview_calendafirst:
                img_shangjia.setRotation(360);
                img_jingying.setRotation(360);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                pvTime.show(layout_search);

                break;

            case R.id.layout_second:
            case R.id.textview_calendasecond:
                img_shangjia.setRotation(360);
                img_jingying.setRotation(360);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                pvTime.show(layout_second);
                break;
            case R.id.btn_search:

                Integer i = startTime.compareTo(endTime);
                if (i > 0) {
                    Toast.makeText(GongNoticeListActivity.this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                } else {

                    getData(token, "", startTime, endTime, 1);
                }

                break;
        }
    }


    @Override
    public void onItemClickListener(View view, int pos, List<NoticeModel.DataBean> myLiveList) {
        Intent intent;
        switch (view.getId()) {
      /*      case R.id.text_manager:
                intent = new Intent(GongNoticeListActivity.this, CommodityShopManagerActivity.class);
                startActivity(intent);
                break;*/
            default:
//                        startActivity(new Intent(GongNoticeListActivity.this, NoticeDetailActivity.class));
                intent = new Intent(GongNoticeListActivity.this, NoticeDetailActivity.class);
                intent.putExtra("announceId", myLiveList.get(pos).getId());
                intent.putExtra("position", pos + "");

                intent.putExtra("noticeIds", noticeIds.toString());
                intent.putExtra("startTime", startTime);
                intent.putExtra("endTime", endTime);
                startActivity(intent);
        }
    }


    public void getCaneda() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2020, 1, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(y, m, d);
        pvTime = new TimePickerBuilder(GongNoticeListActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_search:
                    case R.id.textview_calendafirst:
                        textview_calendafirst.setText(getTime(date));
                        startTime = getTime(date);
                        Integer i = startTime.compareTo(endTime);
                        if (i > 0) {
                            Toast.makeText(GongNoticeListActivity.this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
//                            getData(token, date_Send, "");
                            dataList.clear();
                            getData(token, "", startTime, endTime, 1);
                        }

                        break;
                    case R.id.textview_calendasecond:
                    case R.id.layout_second:
                        textview_calendasecond.setText(getTime(date));
                        endTime = getTime(date);
                        Integer i1 = startTime.compareTo(endTime);
                        if (i1 > 0) {
                            Toast.makeText(GongNoticeListActivity.this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
//                            getData(token, date_Send, "");
                            dataList.clear();
                            getData(token, "", startTime, endTime, 1);
                        }

                        break;
                }

            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                                img_shangjia.setRotation(180);
                                img_jingying.setRotation(180);
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                                img_shangjia.setRotation(180);
                                img_jingying.setRotation(180);
                                pvTime.dismiss();
                            }
                        });

                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))
                .setOutSideCancelable(false)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public void onEventMainThread(Integer integer) {
        if (integer == 17) {
            getData(token, "", "", "", 1);
        }

    }

}




